import * as mobx from 'mobx';
import { ListStore } from '../listStore';
import {message} from 'antd';
import {WeaLocaleProvider} from 'ecCom';
import * as WORKFLOW_CUSTOMFORM from '../../apis/customReportForm';
import * as API from '../../apis/standCustomReport';
const { observable, action } = mobx;
const getLabel = WeaLocaleProvider.getLabel;
import {Modal} from 'antd';
export class WFViewReportStore extends ListStore{

    key = 0;     //标志tabs
    tabs = [];     //tabs数据
    @observable resultTitle = '';   //搜索结果的title
    @observable requestidRange = ''   //查看弹出框的requestids
    @observable loadData = true;
    reportid = '';     //记录打开的报表id
    hasFormRight = false;   //是否有赋权;

    rightKey = '';
    @observable dataRanage = '0';

    selectOption = [];
    titleLabel = '';
    selectLabel = '';
    dataRanageLabel = '';
    dataRanageInfo1 = '';
    dataRanageInfo2 = '';
    conditionLabel = '';
    @observable renderComponent = '';
    @observable exportExcelUrl = '';
    @observable exportInfo = [];
    timer = null;
    constructor () {
        super();
        this.switchTabs = this.switchTabs.bind(this);
        this.initDatas = this.initDatas.bind(this);
        this.doViewSearch = this.doViewSearch.bind(this);
        this.loadDatas = this.loadDatas.bind(this);
        this.clearState = this.clearState.bind(this);
        this.updateConfigItem  = this.updateConfigItem.bind(this);
        this.setState  = this.setState.bind(this);
        this.exportExcel = this.exportExcel.bind(this);
        this.setLoadData = this.setLoadData.bind(this);
        this.loadExportInfo = this.loadExportInfo.bind(this);
    }

    @action

    setState (states = {},callback = () => {},callbackArgument = {}) {
        let keys = Object.keys(states);
        keys.map(item => {
            this[item] = states[item];
        })

        callback(callbackArgument);
    }

    @action('reset Tabs')
    resetTabs = (cur,next) => {
        this.loading = true;
        this.tabs = cur;
        setTimeout(()=>{
           this.tabs = next;
           this.loading = false;
        },0)
    }

    setLoadData(bool = false) {
        if(this.loadData != bool)  this.loadData = bool;
    }

    initDatas (params = {}) {
        // 初始加载
        this.loading = true;
        this.key = params.templateid;

        WORKFLOW_CUSTOMFORM.getCRQuery(params).then((datas)=>{
            const tabs = datas.tabs.map((item,index)=>{if (Number(params.templateid) === Number(item.key)){
                    let obj = {...item,config:[...datas.configs],dataRanage:''};
                    if(datas.hasFormRight) {
                        obj.dataRanage = datas.rightInfo.dataRanage;
                    }
                    return obj;
                }else {
                    return {...item,config:[],dataRanage:''};
                }
            });

            this.tabs = tabs;
            this.reportid = params.reportid || '';
            this.title = datas.reportname;
            this.hasFormRight = datas.hasFormRight;

            if(datas.hasFormRight){
                this.rightKey = datas.rightKey;
                this.dataRanage = datas.rightInfo.dataRanage;
                this.selectOption = datas.rightInfo.selectOption;
                this.titleLabel = datas.rightInfo.titleLabel;
                this.selectLabel = datas.rightInfo.selectLabel;
                this.dataRanageLabel = datas.rightInfo.dataRanageLabel;
                this.dataRanageInfo2 = datas.rightInfo.dataRanageInfo2;
                this.dataRanageInfo1 = datas.rightInfo.dataRanageInfo1;
                this.conditionLabel = datas.rightInfo.conditionLabel;
            }

            this.loading = false;
        })

    }

    loadDatas (type = 'shiftTabs',addTemplateid = 0) {      //切换tabs，添加模板，删除模板，修改模板后，加载数据

        this.loading = true;
        let templateid = this.key;
        const reportid = this.reportid;
        const hasFormRight = this.hasFormRight;
        let newParams = {reportid,templateid};

        let timer = setTimeout(()=>{
            if (type === 'edit') {
                //编辑模板
                this.tabs.map((item,index)=>{
                    if (templateid === item.key){
                        this.tabs[index].config = [];
                        WORKFLOW_CUSTOMFORM.getCRQuery(newParams).then((datas)=>{
                            this.tabs[index].config = [...datas.configs];
                            if(hasFormRight) {
                                this.tabs[index].dataRanage = datas.rightInfo.dataRanage;
                            }
                            this.loading = false;
                        })

                    }
                });
            } else if (type === 'add') {
                //添加模板
                templateid = addTemplateid;
                WORKFLOW_CUSTOMFORM.getCRQuery({reportid,templateid}).then((datas)=>{
                    let newItem = datas.tabs.filter((item1,index1)=>{
                        let flag = true;
                        flag = this.tabs.every((item2,index2)=>{
                            if ( item1.key === item2.key ) {
                                flag = false;
                            }
                            return flag;
                        });
                        return flag;
                    });

                    let obj = {...newItem[0],config:[...datas.configs],dataRanage:''};

                    if(hasFormRight) {
                        obj.dataRanage = datas.rightInfo.dataRanage;
                    }

                    this.tabs.push(obj);
                    this.switchTabs(addTemplateid);
                    // this.loading = false;
                })
            } else if (type === 'delete') {
                // 删除模板
                this.tabs = this.tabs.filter((item,index)=>{
                    if (item.key === templateid) {
                        return false;
                    }else {
                        return true;
                    }
                })
                this.switchTabs(0);

            }
            clearTimeout(timer)
        },0);
    }

    switchTabs (key = 0) {

        this.key = key;
        const templateid = key;
        const reportid = this.reportid;
        const hasFormRight = this.hasFormRight;
        let newParams = {reportid,templateid};
        this.loading = true;

        this.tabs.map((item,index)=>{
            if (templateid === item.key) {
                if (item.config.length === 0){
                    WORKFLOW_CUSTOMFORM.getCRQuery(newParams).then((datas)=>{
                        const { configs = [], hasFormRight, rightInfo = {} } = datas;
                        if(hasFormRight){
                            const { dataRanage } = rightInfo;
                            item.dataRanage = dataRanage;
                            this.dataRanage = dataRanage;
                        }
                        item.config = [...configs];
                        this.loading = false;
                    })
                } else {
                    let config = [...item.config];
                    item.config = [];
                    if(hasFormRight){
                        this.dataRanage = item.dataRanage;
                    }
                    let timer = setTimeout(()=>{
                        item.config = [...config];
                        this.loading = false;
                    },0);
                }
            }
        });

        // this.loadDatas('shiftTabs')
    }

    updateConfigItem(index,configItemIndex,updateObj) {
        let needRenderCom =  false;
        this.tabs && this.tabs.forEach((tabItem) => {
            const {config = []} = tabItem;
            if(config && config.length > 0) {
                const configitem = config[index];
                configitem.config[configItemIndex] = updateObj;

                needRenderCom = true;
            }
        });

        if(needRenderCom) this.renderComponent  = new Date().getTime();
    }

    doViewSearch (params = {}) {
        this.loading = true;
        WORKFLOW_CUSTOMFORM.getCRViewSearch(params).then((datas)=>{
            const { sessionkey } = datas;
            this.tableStore.getDatas(sessionkey, params.current || 1);
            this.resultTitle = params.title;
            this.key = params.tabKey;
            this.loading = false;
            this.exportInfoParams = {reportid:params.reportid};
            this.loadExportInfoInterval();
        });
    }

    exportExcel(bool = false,reportid) {
        const {dataKey} = this.tableStore;
        const tempThis = this;
        let params = {tableKey:dataKey,reportid:reportid,filename:this.title,from:'newReport'};
        API.exportExcel(params).then((res) => {
            const code = res.code;
            const data = res.data;
            if(code == 0 ) {
                Modal.warning({
                    title: getLabel(131329, '信息确认'),
                    content: data,
                    okText: getLabel(83446, '确定'),
                    onOk() {
                        setTimeout(tempThis.loadExportInfoInterval, 2000);
                    },
                })
            }
            setTimeout(this.loadExportInfoInterval,2000);
        });
    }

    downloadExcel = (url = '',keyid = '') => {
        if(url) this.exportExcelUrl = url;
        let params = {...this.exportInfoParams,'method':'update',id:keyid,status:url ? '2':'3'};
        API.exportTask(params).then((res)=>{
            const {datas = []} = res;
            this.loadExportInfoInterval();
        })
    }

    loadExportInfo = () => {
        if(this.loadData) {
            this.setLoadData(false);
            API.exportTask({...this.exportInfoParams, 'method': 'list','from':'newReport'}).then((res = {}) => {
                const {datas = []} = res;
                this.exportInfo = datas;

                let tmpdatas = datas.filter((item = {}) => item.status == 0);
                if (tmpdatas.length <= 0 && this.timer) {
                    clearInterval(this.timer);
                    this.timer = null;
                }
                this.setLoadData(true);
            })
        }
    }


    loadExportInfoInterval = () => {
        if(this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
        this.loadExportInfo();
        this.timer = setInterval(this.loadExportInfo,2000);
    }

    cancelTask = (keyid = '')=>{
        let params = {id:keyid , 'method':'cancel'};
        API.cancelTask(params).then((res)=>{
            this.loadExportInfoInterval();
        })

    }

    clearState () {
        this.key = 0;
        this.tabs = [];
        this.title = '';
        this.reportid = '';
        this.exportExcelUrl = '';
        this.resetTable();
    }

}